package com.qd.core.service.user;

import com.cdqidi.core.weixinmanager.model.MiddleUser;
import com.cdqidi.core.weixinmanager.service.MiddleUserService;
import com.qd.common.sys.domain.entity.login.LoginUserDTO;
import com.qd.common.sys.domain.login.AppUserExtend;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.enums.RemoteEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Optional;

/**
 * 用户验证处理
 * 按照用户名登录
 *
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxUserDetailServiceImpl implements CustomUserDetailService {
    @Resource
    private  MiddleUserService middleUserService;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (log.isDebugEnabled()) {
            log.debug("小程序登录： {}", username);
        }
        final MiddleUser middleUser = Optional.ofNullable(middleUserService.getById(username)).orElseThrow(() -> new UsernameNotFoundException("用户ID不存在: " + username));
        final LoginUserDTO loginUserDTO = new LoginUserDTO();

        AppUserExtend appLoginUserDTO = new AppUserExtend();
        appLoginUserDTO.setAppId(middleUser.getAppId())
                .setOpenid(middleUser.getOpenid())
                .setUnionId(appLoginUserDTO.getUnionId())
                .setMobile(middleUser.getMobile());
        if(StringUtils.hasLength(middleUser.getHeadImg())){
            appLoginUserDTO.setAvatar(middleUser.getHeadImg());
        }
        if(StringUtils.hasLength(middleUser.getNickName())){
            appLoginUserDTO.setNickName(middleUser.getNickName());
        }
        loginUserDTO.setPersonId(middleUser.getUserId());
        loginUserDTO.setAppUserExtend(appLoginUserDTO);

        final LoginUser loginUser = new LoginUser(loginUserDTO, Collections.emptySet());
        loginUser.setUserId(loginUserDTO.getPersonId());
        return loginUser;
    }


    @Override
    public Boolean remote(String platform) {
        return platform.equals(RemoteEnum.MINI_PROGRAM.getMsg());
    }
}
